import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Table } from 'antd';
import _ from 'lodash';

class NodeTable extends Component {
  constructor(props) {
    super(props);
    this.state = {
      tableData: [],
      page: 1,
      pageSize: 20
    };
  }
  // eslint-disable-next-line
  UNSAFE_componentWillReceiveProps(nextProps) {
    let newData = nextProps.data;
    if (newData !== this.state.data) {
      this.setState({ tableData: newData });
    }
  }

  onTableChange = ({ current: page, pageSize }) => {
    let { data } = this.props;
    let { tableData } = this.state;
    tableData = _.slice(data, (page - 1) * pageSize, page * pageSize);
    this.setState({ tableData, page, pageSize });
  };

  render() {
    const { data } = this.props;
    const { tableData, page, pageSize } = this.state;
    const count = data.length;
    const columns = [
      {
        title: 'CPU 利用率',
        dataIndex: 'cpu',
        render: item => <span style={{ color: item >= 80 ? '#ff0000' : '' }}>{item || '-'}%</span>
      },
      {
        title: '内存利用率',
        dataIndex: 'memory',
        render: item => <span style={{ color: item >= 80 ? '#ff0000' : '' }}>{item || '-'}%</span>
      },
      {
        title: '磁盘利用率',
        dataIndex: 'disk',
        render: item => <span style={{ color: item >= 80 ? '#ff0000' : '' }}>{item || '-'}%</span>
      },
      {
        title: '发送流量',
        dataIndex: 'netSend',
        render: item => `${item || '-'} kb/s`
      },
      {
        title: '接收流量',
        dataIndex: 'netRecive',
        render: item => `${item || '-'} kb/s`
      },
      {
        title: '更新时间',
        dataIndex: 'created'
      }
    ];
    const pagination = {
      total: count,
      current: page,
      pageSize: pageSize,
      showQuickJumper: true,
      pageSizeOptions: ['20', '40', '60'],
      showSizeChanger: true,
      showTotal: num => `共 ${num} 条`,
      size: 'small'
    };
    return (
      <div>
        <div>当前共有 “{count}” 条数据</div>
        <Table
          columns={columns}
          dataSource={tableData}
          pagination={pagination}
          onChange={this.onTableChange}
        />
      </div>
    );
  }
}

NodeTable.propTypes = {
  data: PropTypes.array
};

export default NodeTable;
